<template>
  <info-page-container @goListPage="cancel">
    <div class="info-data-container full-container flex-column">


      <div class="info-base-data">
        <el-form :rules="rules" :model="dataItem" ref="baseForm" size="small"
                 label-width="80px">
          <el-form-item label="保单名称" prop="orderName">
            <el-input
              v-model="dataItem.orderName"
              placeholder="请输入保单名称"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="保单编号" prop="orderNo">
            <el-input
              v-model="dataItem.orderNo"
              placeholder="请输入保单编号"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="险种" prop="insuranceTypeId">
            <el-select v-model="dataItem.insuranceTypeId" placeholder="请选择险种">
              <el-option
                v-for="item in insuranceList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div class="list-container">
        <layout-container title="农户列表">
          <template slot="title">
            <div class="flex-row">
              <div class="important-txt">
                投保农户：{{ listData.length }} 户
              </div>
              <div class="important-txt" style="margin-left: 20px">
                总面积：{{ sumArea }} 亩
              </div>
              <div class="important-txt" style="margin-left: 20px">
                总金额：{{ totalMoney }} 元
              </div>
            </div>
          </template>
          <template slot="bt">
            <el-button class="diy-bt txt-bt" icon="el-icon-plus" size="mini" @click="addFarmer(null)">
              添加农户
            </el-button>
          </template>
          <template>
            <el-table
              class="diy-table"
              :data="listData"
              style="width: 100%;" height="100%">
              <el-table-column
                prop="farmerNo"
                label="农户编号">
              </el-table-column>
              <el-table-column
                prop="farmerName"
                label="农户名称">
              </el-table-column>
              <el-table-column
                prop="farmerIdentity"
                width="180"
                label="身份证号">
              </el-table-column>
              <el-table-column
                prop="sumArea"
                label="投保面积(亩)">
                <template slot-scope="scope">
                    <span class="important-txt">
                    {{ scope.row.sumArea }}
                    </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="money"
                label="投保总额(元)">
                <template slot-scope="scope">
                    <span class="important-txt">
                    {{ scope.row.money }}
                    </span>
                </template>
              </el-table-column>

              <el-table-column width="170" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="locationByData(chitLayerId,scope.row,'农户信息')"
                  >定位
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="addFarmer(scope.row)"
                  >详情
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="delFarmer(scope.row)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>

            </el-table>
          </template>
        </layout-container>
      </div>

      <div class="handle-bt-container flex-row">
        <el-button class="diy-bt" icon="el-icon-refresh" size="mini" @click="save">保存</el-button>
        <el-button class="diy-bt" icon="el-icon-refresh" size="mini" @click="cancel">取消</el-button>
      </div>

    </div>
  </info-page-container>
</template>

<script>
import {infoPageMixins} from "@/views/business/mixins/infoPageMixins";
import {pageBaseMapMixins} from "@/views/business/mixins/pageBaseMapMixins";
import {GEOMETRY_TYPE, HANDLE_TYPE, REFRESH_PAGE_TYPE} from "@/views/business/constantData";
import {addInsurance, getInsuranceInfo, updateInsurance} from "@/api/business/underwritingFile";
import {getDataAdminList} from "@/api/business/dataAdministration";
import {isArr} from "@/utils/arrayUtil";
import {addFarmer, getAllPlot, updateFarmer} from "@/api/business/userManagement";
import item from "@/layout/components/Sidebar/Item.vue";
import {GET_LOCATE_SYMBOL} from "@/utils/SymbolUtils";

export default {
  mixins: [infoPageMixins, pageBaseMapMixins],
  data() {
    return {
      listData: [],
      chitLayerId: 'chit',
      insuranceList: [],
      plotLayerId: 'plot',
      farmerPlotId: 'farmerPlotId',
      rules: {
        orderName: [
          {required: true, message: '保单名称不能为空', trigger: 'blur'},
        ],
        orderNo: [
          {required: true, message: '保单编号不能为空', trigger: 'change'},
        ],
        insuranceTypeId: [
          {required: true, message: '险种不能为空', trigger: 'change'},
        ],
      },
    }
  },
  computed: {
    sumArea() {
      let {listData} = this
      return isArr(listData) ? _.round(_.sum(_.map(listData, item => parseFloat(item.sumArea)))) : 0
    },
    totalMoney() {
      let {listData} = this
      return isArr(listData) ? _.round(_.sum(_.map(listData, item => parseFloat(item.money)))) : 0
    },
  },
  methods: {
    cancel() {
      this.removeFarmerLayer()
      this.goListPage(REFRESH_PAGE_TYPE.NO_REFRESH)
    },
    saveFinish() {
      this.removeFarmerLayer()
      this.goListPage(REFRESH_PAGE_TYPE.REFRESH)
    },
    removeFarmerLayer() {
      this.removeRender()
      this.removeLayer({layerId: this.chitLayerId})
    },
    save() {
      let owner = this
      this.$refs.baseForm.validate((valid) => {
        if (valid) {
          owner.startLoading()
          let {dataItem: {id, orderName, orderNo, insuranceTypeId}, listData: archiveBodies} = owner;
          const params = {
            id,
            orderName,
            orderNo,
            insuranceTypeId,
            archiveBodies,
          }
          if (id == null || id == '') {
            addInsurance(params).then(res => {
              this.$message({
                message: '添加成功',
                type: 'info'
              })
            }).finally(() => {
              owner.endLoading()
              this.saveFinish()
            })
          } else {
            updateInsurance(params).then(res => {
              this.$message({
                message: '修改成功',
                type: 'info'
              })
            }).finally(() => {
              owner.endLoading()
              this.saveFinish()
            })
          }
        }
      });
    },
    setCurrentItem(currentItem) {
      this.startLoading()
      let owner = this
      if (currentItem != null && currentItem?.id != null && currentItem?.id !== '') {
        this.currentHandleType = HANDLE_TYPE.UPDATE;
        getInsuranceInfo(currentItem).then(res => {
          let {data: {insuranceOrder: {id, orderName, orderNo, insuranceTypeId}, result}} = res;
          owner.dataItem = {id, orderName, orderNo, insuranceTypeId};
          owner.listData = result.map(item => {
            let {
              plots: basePlots,
              farmerFarmer: {farmerName, farmerIdentity, farmerNo, id: farmerId,},
              money,
              endTime,
              startTime
            } = item;
            const sumArea = _.round(_.sum(basePlots.map(cItem => cItem.geometryArea)), 2)
            const plotIds = basePlots.map(cItem => cItem.id)
            return {
              plotIds,
              farmerName,
              farmerIdentity,
              farmerNo,
              farmerId,
              money,
              startTime,
              endTime,
              sumArea
            }
          })
          owner.addAllChitDataToMap()
        }).finally(() => {
          owner.endLoading()
        });
      } else {
        this.currentHandleType = HANDLE_TYPE.ADD
        owner.listData = []
        owner.dataItem = {
          archiveBodies: [
            {
              //  保险失效日期
              endTime: "2019-08-24",
              //  农户Id
              farmerId: 0,
              //  投保金额
              money: 0,
              //  地块
              plotIds: [],
              //  保险生效日期
              startTime: "2019-08-24"
            }
          ],
          //  险种id
          insuranceTypeId: null,
          //  保单名称
          orderName: '',
          //  保单编号
          orderNo: ''
        };
      }
      owner.endLoading();
    },
    addFarmer(farmerItem) {
      this.$emit('goInfoPage', farmerItem)
    },
    delFarmer(farmerItem) {
      this.listData = this.listData.filter(item => item.farmerId !== farmerItem.farmerId);
      this.addAllChitDataToMap()
    },
    setFarmer({farmerChit, removeFarmerId}) {
      let {farmerId} = farmerChit
      let {listData} = this;
      if (listData.some(item => item.farmerId == farmerId)) {
        this.listData = _.cloneDeep(this.listData).map(cItem => {
          if (cItem.farmerId == farmerId) {
            cItem = _.cloneDeep(farmerChit)
          }
          return cItem
        })
      } else {
        this.listData.push(farmerChit)
      }
      if (removeFarmerId != null && removeFarmerId !== '') {
        this.listData = this.listData.filter(item => item.farmerId != removeFarmerId)
      }
      this.addAllChitDataToMap()
    },
    async addAllChitDataToMap() {
      this.removeLayer({layerId: this.chitLayerId})
      let {listData} = this;
      if (!isArr(listData)) return;
      let plotIdList = listData.map(item => item.plotIds).reduce((v1, v2) => [...v1, ...v2])
      let where = ''
      plotIdList.forEach((id, index) => {
        where = index != 0 ? `${where} or id = '${id}'` : `id = '${id}'`
      })
      let currentFarmerFeatures = await this.getGraphicByGeometryAndWhere({layerId: this.farmerPlotId, where});
      if (isArr(currentFarmerFeatures)) {
        const geometryType = GEOMETRY_TYPE.POLYGON;
        const txtFileList = [
          {
            value: 'farmerName',
            label: '农户名称',
          },
          {
            value: 'plotNo',
            label: '地块编号',
          },
          {
            value: this.areaFiled,
            label: '面积',
            suffix: ' 亩'
          },
        ]
        await this.addLayer({
          layerId: this.chitLayerId,
          source: currentFarmerFeatures,
          rendererSymbol: {
            type: "simple-fill",
            color: [255, 255, 0, 0.1],
            outline: {
              color: [255, 255, 0, 1],
              width: 2
            }
          },
          geometryType,
          txtFileList,
          txtColor: '#fff',
          fontSize: 15
        })
      }
    },
    locationByData(layerId, row, popupTitle) {
      let {farmerId} = row
      const where = `farmerId = '${farmerId}'`
      this.locationByWhere({layerId, where, openPopupFlag: true, popupTitle})
    },
    async addBaseLayer() {
      let plotList = await getAllPlot()
      let {rows} = plotList;
      const geometryType = GEOMETRY_TYPE.POLYGON;
      const txtFileList = []
      let graphicList = _.map(rows, item => {
        let {farmerFarmer: {farmerName, id: farmerId,}, id, plotNo, geoData, geometryArea} = item
        return {
          attributes: {farmerId: farmerId.toString(), farmerName, id: id.toString(), geometryArea, plotNo},
          geoData
        }
      })
      await this.addLayerByGraphicData({
        layerId: this.farmerPlotId,
        rendererSymbol: {
          type: "simple-fill",
          color: [255, 255, 0, 0],
          outline: {
            color: [255, 255, 0, 0],
            width: 2
          }
        },
        graphicList,
        geometryType,
        txtFileList
      })
    },
    initMonitor() {
      this.openMonitor({layerId: this.chitLayerId, backFun: this.setCurrentFeature})
    },
    setCurrentFeature({point, layer, features}) {
      const popupTitle = '农户信息'
      this.locationByFeatures({layerId: layer.id, features, openPopupFlag: true, popupTitle, point})
    },
  },
  async created() {
    await this.awaitMapLoaded()
    await this.addBaseLayer()
    getDataAdminList().then(res => {
      this.insuranceList = _.map(res.rows, item => {
        let {typeName: label, id: value} = item;
        return {label, value: value.toString()}
      })
    })
  }
};
</script>

<style scoped lang="scss">
.info-data-container {
  .info-base-data {
    height: 20% !important;
    max-height: 20% !important;
  }

  .list-container {
    height: 70% !important;
  }

  .handle-bt-container {
  }
}
</style>
